<?php

/**
 * Created by PhpStorm.
 * User: silov
 * Date: 16/3/29
 * Time: 16:21
 */
namespace Server\Controller;

use Think\Controller;
use Think\Upload;

class UeditorController extends Controller
{
    public function ueditor() {
        $action = $this->params['action'];
        $config = [
            /* 上传图片配置项 */
            "imageActionName" => "uploadimage", /* uploadimage 执行上传图片的action名称 */
            "imageFieldName" => "upfile", /* 提交的图片表单名称 */
            "imageMaxSize" => 10240000, /* 上传大小限制，单位B */
            "imageAllowFiles" => [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */
            "imageCompressEnable" => true, /* 是否压缩图片,默认是true */
            "imageCompressBorder" => 1600, /* 图片压缩最长边限制 */
            "imageInsertAlign" => "none", /* 插入的图片浮动方式 */
            "imageUrlPrefix" => STATIC_URL ."/upload/",
            // "imageUrlPrefix" => str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'])), /* 图片访问路径前缀 */
            "imagePathFormat" => "upload/img/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
            /* {filename} 会替换成原文件名,配置这项需要注意中文乱码问题 */
            /* {rand:6} 会替换成随机数,后面的数字是随机数的位数 */
            /* {time} 会替换成时间戳 */
            /* {yyyy} 会替换成四位年份 */
            /* {yy} 会替换成两位年份 */
            /* {mm} 会替换成两位月份 */
            /* {dd} 会替换成两位日期 */
            /* {hh} 会替换成两位小时 */
            /* {ii} 会替换成两位分钟 */
            /* {ss} 会替换成两位秒 */
            /* 非法字符 \ =>* ? " < > | */
            /* 具请体看线上文档=>fex.baidu.com/ueditor/#use-format_upload_filename */
        ];

        switch ($action) {
            case 'config':

                $this->ajaxReturn($config, "JSON");
                break;
            /* 上传图片 */
            case 'uploadimage':
                $this->uploadImg();
                break;
            default:
                $this->ajaxReturn(['statue'=> '请求地址出错'], "JSON");
                break;
        }
    }


    public function uploadImg() {
        $fieldName = "upfile";

        $upload = new Upload();
        $upload->maxSize = 1024*1024*2;
        $upload->exts = ['jpg', 'jpeg', 'gif', 'png'];
        $upload->rootPath = ROOT_PATH . '/Static/upload/img/' ;

        $info = $upload->upload($_FILES);

        //$filePath =  getNewPicsName($fileInfo['fileName'],640);
        $fileInfo =  $info[$fieldName];
        if (!$fileInfo) {
            $this->ajaxReturn(array('status' => 0, 'msg' => $upload->getError()));
            exit;
        } else {
            $data = array(
                'state'     => 'SUCCESS',
                'url'       => '/img/'. $fileInfo['savepath'] .'/'.$fileInfo['savename'],
                'title'     => $fileInfo['name'],
                'original'  => $fileInfo['name'],
                'type'      => $fileInfo['type'],
                'size'      => $fileInfo['size']
            );
        }
        $this->ajaxReturn($data,"JSON");
    }
}